//
//  DXPictureView.swift
//  weiBoOfSwift
//
//  Created by simon on 15/12/11.
//  Copyright © 2015年 simon. All rights reserved.
//

import UIKit
import SnapKit
let itemMargin:CGFloat = 3
let itemWH = Int( KScreenW -  2 * (KStatuesCellMargin + itemMargin))/3
let KReuseIdentifier = "KPictureReuseIdentifier"
class DXPictureView: UICollectionView,UICollectionViewDataSource {

    
    var pictures:[DXStatuesPictureModel]?{
    
        didSet{
             let itemCount = pictures?.count ?? 0
            self.messLaebl.text = "\(itemCount)"
            self.snp_updateConstraints { (make) -> Void in
            make.size.equalTo(calculateSize(itemCount)).constraint
                
                reloadData()
            }
    }
}
 
//    重写构造方法
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
//        注册cell
        registerClass(DXPictureItem.self, forCellWithReuseIdentifier: KReuseIdentifier)
//        初始化UI
        setUpUI()
        
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // MARK: - 初始化UI
    private func setUpUI(){
//        设置item的布局
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        
        layout.minimumLineSpacing = itemMargin
        
        layout.minimumInteritemSpacing = itemMargin
        
        layout.itemSize = CGSizeMake(CGFloat(itemWH), CGFloat(itemWH))
        
//       背景色
        backgroundColor = UIColor.init(white: 0.95, alpha: 1)
//        设置代理
        dataSource = self
        delegate = self
//        添加子控件
        addSubview(messLaebl)
        messLaebl.hidden = true

        
//        添加约束
        messLaebl.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self)
            make.size.equalTo(CGSizeMake(80, 80))
        }    
    }
//    懒加载
    lazy var messLaebl:UILabel = UILabel()

}
// MARK:  UICollectionViewDataSource
extension DXPictureView{

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
//        logPrint("\(pictures?.count ?? 0)")
        
        return pictures?.count ?? 0
        
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let item = collectionView.dequeueReusableCellWithReuseIdentifier(KReuseIdentifier, forIndexPath: indexPath) as! DXPictureItem
        
        item.pic_urlString = pictures![indexPath.item].thumbnail_pic
        
        return item
    }

    //    MARK:- 计算自身行高
    private func calculateSize(count:Int)->CGSize{
        //       行数
        let col = count==4 ? 2 : ( count < 3 ? count : 3 )
        //        列数
        let row = count==0 ? 0 : ((count - 1 )/3 + 1)
        
        let size = CGSizeMake(CGFloat(col) * CGFloat(itemWH) + CGFloat(col - 1) * itemMargin , CGFloat(row) * CGFloat(itemWH) + CGFloat(row - 1) * itemMargin )
        
        return  count==0 ? CGSizeZero : size
        
    }
    
}
//MARK:图片浏览器的代理
extension DXPictureView:SDPhotoBrowserDelegate{
    
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
        
        // 设置 indexPath
        let index = NSIndexPath(forItem: index, inSection: 0)
        // 通过 indexPath 获取到其对应的 cell
        if let cell = self.cellForItemAtIndexPath(index) as? DXPictureItem {
            return cell.imgView.image
        }
        return nil

    }
    
    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
        let urlString = pictures![index].thumbnail_pic!.stringByReplacingOccurrencesOfString("thumbnail", withString: "bmiddle")
        
        return NSURL(string: urlString)
    }



}

//MARK:  collectiveView的代理方法
extension DXPictureView:UICollectionViewDelegate{

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let browser = SDPhotoBrowser()
        browser.sourceImagesContainerView = self
        // 图片张数
        browser.imageCount = pictures?.count ?? 0
        browser.currentImageIndex = indexPath.item
        browser.delegate = self
        browser.show()

    }

}

//// MARK:  pictureItem
class DXPictureItem: UICollectionViewCell {
        var pic_urlString:String?{
    
    didSet{
    
    if let  urlString = pic_urlString {
//                logPrint(urlString)
        gifIcon.hidden = urlString.hasSuffix(".gif") ? false : true

    imgView.sd_setImageWithURL(NSURL(string: urlString), placeholderImage: UIImage(named: "timeline_image_placeholder"))
    }
    }
}

override init(frame: CGRect) {
    super.init(frame: frame)
    
//    contentView.backgroundColor = radomCorlor()
    //        添加子控件
    contentView.addSubview(imgView)
    contentView.addSubview(gifIcon)
    //        添加约束
    imgView.snp_makeConstraints { (make) -> Void in
        make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
    }
    gifIcon.snp_makeConstraints { (make) -> Void in
        make.trailing.equalTo(imgView)
        make.bottom.equalTo(imgView)
    }
    
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
//  图片
lazy var imgView:UIImageView = {
    let imgView = UIImageView()
    
    imgView.contentMode = .ScaleAspectFill
    
    imgView.clipsToBounds = true
    
    return imgView
    
}()
    lazy var gifIcon:UIImageView = {
    let gifIcon = UIImageView(image: UIImage(named: "timeline_image_gif"))
    gifIcon.hidden = true
    return gifIcon
    }()

}



